#include <iostream>
#include <fstream>
#include <sstream>
#include <map>
#include <string>
using namespace std;

class Dictionary{
public:
    void read(const string & filename){
        ifstream ifs(filename);
        if(!ifs){
            cerr << "ifs open file fail" << endl;
            return;
        }

        //因为磁盘读写速度慢，应该尽量减少次数
        /* string word; */
        /* while(ifs >> word){ */
        /* } */

        string line;
        while(getline(ifs,line)){
            istringstream iss(line);
            string word;
            while(iss >> word){
                //处理单词
                string newWord = dealWord(word);

                //将单词的信息插入到map
                if(newWord != string()){
                    //一步到位
                    //如果是已存在的单词，会将frequency+1
                    //如果是新的单词，会插入一个新的pair
                    //string内容为新单词，int为0，在加为1
                    ++_map[newWord];
                }
            }
        }

        ifs.close();
    }

    string dealWord(string & word){
        for(size_t idx = 0; idx != word.size(); ++idx){
            if(!isalpha(word[idx])){
                return string(); //用空串进行替换
            }else if(isupper(word[idx])){
                word[idx] = tolower(word[idx]);//大写转小写
            }
        }
        return word;
    }

    void store(const string & filename){
        ofstream ofs(filename);
        if(!ofs){
            cerr << "ofs open file fail" << endl;
            return;
        }

        /* for(size_t idx = 0; idx != _map.size(); ++idx){ */
        /*     ofs << _map[idx]._word << " " */ 
        /*         << _map[idx]._frequency << endl; */
        /* } */

        map<string,int>::iterator it = _map.begin();
        /* auto it = _map.begin(); */
        for(; it != _map.end(); ++it){
            ofs << it->first << " " << it->second << endl;
        }

        ofs.close();
    }
private:
    //string代表word，int代表frequency
    map<string,int> _map;
};

void test0(){
    Dictionary dict;
    cout << "before reading..." << endl;
    time_t beg = time(NULL);
    dict.read("The_Holy_Bible.txt");
    time_t end = time(NULL);
    cout << "time: " << (end - beg) << "s" << endl;
    cout << "after reading..." << endl;
    dict.store("dictMap.dat");
}

int main(void){
    test0();
    return 0;
}
